package service

import (
	"errors"
	"github.com/spf13/viper"
	"net/url"
	"shortURL/model"
	"shortURL/pkg/errno"
	"shortURL/sequence"
	"shortURL/util"
	"time"
)

type ShorterService struct {
}

func GetShortService() *ShorterService {
	return &ShorterService{}
}

// 获取短链接
func (srv *ShorterService) Short(longUrl string) (shortUrl string, err error) {
	var shortUrlPath string

	for {
		sequencer, err := sequence.GetSequence(viper.GetString("seq_type"))
		if err != nil {
			return "", errno.New(errno.InternalServerError, err)
		}

		seqId, err := sequencer.NextSequence()
		if err != nil {
			return "", errno.New(errno.InternalServerError, err)
		}

		shortUrlPath = util.Int2Str(seqId)
		if util.InSlice(shortUrlPath, viper.GetStringSlice("black_short_url")) {
			continue
		} else {
			break
		}
	}

	// 写入 db
	urlModel := model.NewShort()
	urlModel.LongUrl = longUrl
	urlModel.ShortUrl = shortUrlPath
	urlModel.CreateTime = time.Now()

	_, err = urlModel.Create()
	if err != nil {
		return "", errno.New(errno.InternalServerError, err)
	}

	// generate
	shortUrl = (&url.URL{
		Scheme: viper.GetString("schema"),
		Host:   viper.GetString("domain_name"),
		Path:   shortUrlPath,
	}).String()

	return
}

// 将短链接转换成长链接
func (srv *ShorterService) Expand(shortUrl string) (longUrl string, err error) {
	urlModel, err := model.FindUrLByShortUrl(shortUrl)
	if err != nil {
		return "", errno.New(errno.InternalServerError, err)
	}

	if urlModel == nil {
		return "", errno.New(errno.InternalServerError, errors.New("long url not find"))
	}

	return urlModel.LongUrl, nil
}
